<?php


namespace App\Service;


use Carbon\Carbon;
use Google\Client;
use Illuminate\Support\Facades\Cache;

class Notification
{

    /**
     * 将设备添加到主题
     * @author jeanku
     * @date 2019-11-22
     * @param array $data require 请求数据
     * @return array
     * @throws \Exception
     */
    public static function push($data)
    {
        $url = 'https://fcm.googleapis.com/v1/projects/longhash-notification/messages:send';
        return CurlRequest::setParamType(1)->setHeader(self::getAccessTokenHeader())->post($url, $data);
    }

    /**
     * 推送消息的请求header
     * @date 2019-11-22
     * @return array
     * @throws \Google_Exception
     */
    protected static function getAccessTokenHeader()
    {
        $jsonFile = public_path('/datafile/'.env('GOOGLE_SERVICE_ACCOUNT_JSON_LOCATION'));
        return [
            'Content-Type: application/json',
            'Authorization: Bearer ' . self::getAccessToken($jsonFile),
        ];
    }


    /**
     * 获取access_token的方法，并对accessToken做了缓存处理
     * @param string $configPath require 下载的service-account-file.json文件存放路径
     * @return string
     * @demo AccessToken::getAccessToken('/path/to/service-account-file.json')
     */
    public static function getAccessToken($configPath)
    {
        $cacheKey = 'fcm:google:accesstoken';
        $temp = Cache::get($cacheKey);
        if (empty($temp)) {
            $expiresAt = Carbon::now()->addMinutes(10);
            $temp = self::requestAccessToken($configPath);
            Cache::put($cacheKey, $temp['access_token'], $expiresAt);

            return $temp['access_token'];
        }

        return $temp;
    }


    /**
     * 调用google google-api-php-client 获取access_token 这个是通过google的服务账号授权(用于server端) 不是页面的OAuth授权
     * @param string $configPath option 配置文件路径
     * @return [
     *      'access_token' => 'ya29.*****',             //访问令牌
     *      'expires_in' => 3600,                       //访问令牌过期时间
     *      'token_type' => 'Bearer',                   //token_type
     *      'created' => 1574401624,                    //token 创建时间
     * ]
     * @throws \Google\Exception
     */
    protected static function requestAccessToken($configPath)
    {
        $client = new Client();
        $client->useApplicationDefaultCredentials();
        $client->setAuthConfig($configPath);
        $client->setScopes(['https://www.googleapis.com/auth/firebase.messaging']);     # 授予访问 FCM 的权限
        return $client->fetchAccessTokenWithAssertion();
    }

}
